<?php

namespace App\Http\Controllers;

use Beike\Models\Brand;
use Beike\Models\Product;
use Beike\Models\ProductSku;
use Beike\Models\TaxClass;
use Beike\Models\Category;
use Beike\Models\ProductDescription;
use Beike\Models\ProductCategory;
use Beike\Models\ProductAttribute;
use Beike\Models\Attribute;
use Beike\Models\AttributeDescription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ProductController extends Controller
{
    /**
     * Import product(s) with SKUs, descriptions, categories, and attributes via API
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        try {
            // Define validation rules
            $rules = [
                'products' => 'required|array',
                'products.*.descriptions' => 'required|array|min:1',
                'products.*.descriptions.*.locale' => 'required|string|in:en,zh_cn',
                'products.*.descriptions.*.name' => 'required|string|max:500',
                'products.*.descriptions.*.content' => 'string',
                'products.*.descriptions.*.meta_title' => 'nullable|string|max:500',
                'products.*.descriptions.*.meta_description' => 'nullable|string|max:500',
                'products.*.descriptions.*.meta_keywords' => 'nullable|string|max:500',
                'products.*.category_ids' => 'required|array|min:1',
                'products.*.category_ids.*' => 'exists:categories,id',
                'products.*.images.*' => 'string',
                'products.*.price' => 'required|numeric|min:0',
                'products.*.video' => 'nullable|string|max:191',
                'products.*.position' => 'integer|min:0',
                'products.*.active' => 'required|boolean',
                'products.*.variables' => 'nullable|array',
                'products.*.tax_class_id' => 'integer|min:0',
                'products.*.sales' => 'integer|min:0',
                'products.*.attributes' => 'nullable|array',
                'products.*.attributes.*.attribute_id' => 'required|exists:attributes,id',
                'products.*.attributes.*.attribute_value_id' => 'required|exists:attribute_values,id',
                'products.*.skus' => 'required|array|min:1',
                'products.*.skus.*.variants' => 'nullable|array',
                'products.*.skus.*.position' => 'integer|min:0',
                'products.*.skus.*.images' => 'array',
                'products.*.skus.*.images.*' => 'string',
                'products.*.skus.*.model' => 'required|string|max:191',
                'products.*.skus.*.sku' => 'required|string|max:191|distinct',
                'products.*.skus.*.price' => 'required|numeric|min:0',
                'products.*.skus.*.origin_price' => 'required|numeric|min:0',
                'products.*.skus.*.cost_price' => 'required|numeric|min:0',
                'products.*.skus.*.quantity' => 'required|integer|min:0',
                'products.*.skus.*.is_default' => 'required|boolean',
            ];

            // Custom validation for variants indices
            $validator = Validator::make($request->all(), $rules, [], [
                'products.*.skus.*.variants' => 'SKU variants',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'error' => json_encode($validator->errors()),
                ], 422);
            }

            // Begin database transaction
            DB::beginTransaction();

            $importedCount = 0;
            $failedProducts = [];

            foreach ($request->products as $productData) {
                try {
                    // Create product
                    $product = Product::create([
                        'brand_id' => $productData['brand_id']??0,
                        'images' => $productData['images'] ?? null,
                        'price' => $productData['price'],
                        'video' => $productData['video'] ?? '',
                        'position' => $productData['position'] ?? 0,
                        'active' => $productData['active'],
                        'variables' => $productData['variables'] ?? null,
                        'tax_class_id' => $productData['tax_class_id'] ?? 0,
                        'weight' => $productData['weight'],
                        'weight_class' => $productData['weight_class'],
                        'sales' => $productData['sales'] ?? 0,
                    ]);

                    // Create product descriptions
                    foreach ($productData['descriptions'] as $description) {
                        ProductDescription::create([
                            'product_id' => $product->id,
                            'locale' => $description['locale'],
                            'name' => $description['name'],
                            'content' => $description['content'],
                            'meta_title' => $description['meta_title'] ?? '',
                            'meta_description' => $description['meta_description'] ?? '',
                            'meta_keywords' => $description['meta_keywords'] ?? '',
                        ]);
                    }

                    // Create product category associations
                    foreach ($productData['category_ids'] as $categoryId) {
                        ProductCategory::create([
                            'product_id' => $product->id,
                            'category_id' => $categoryId,
                        ]);
                    }

                    // Create product attributes
                    if (!empty($productData['attributes'])) {
                        foreach ($productData['attributes'] as $attribute) {
                            ProductAttribute::create([
                                'product_id' => $product->id,
                                'attribute_id' => $attribute['attribute_id'],
                                'attribute_value_id' => $attribute['attribute_value_id'],
                            ]);
                        }
                    }

                    // Create SKUs with variants as indices
                    foreach ($productData['skus'] as $skuData) {
                        ProductSku::create([
                            'product_id' => $product->id,
                            'variants' => $skuData['variants'],
                            'position' => $skuData['position'] ?? 0,
                            'images' => $skuData['images'] ?? null,
                            'model' => $skuData['model'],
                            'sku' => $skuData['sku'],
                            'price' => $skuData['price'],
                            'origin_price' => $skuData['origin_price'],
                            'cost_price' => $skuData['cost_price'],
                            'quantity' => $skuData['quantity'],
                            'is_default' => $skuData['is_default'],
                        ]);
                    }

                    $importedCount++;
                } catch (\Exception $e) {
                    $failedProducts[] = [
                        'name' => $productData['descriptions'][0]['name'] ?? 'Unknown',
                        'error' => $e->getLine().':'.$e->getMessage(),
                    ];
                }
            }

            // Commit transaction
            DB::commit();

            // Prepare response
            $response = [
                'status' => 'success',
                'message' => "Imported {$importedCount} products successfully",
                'failed' => $failedProducts,
            ];

            return response()->json($response, 201);

        } catch (\Exception $e) {
            // Rollback transaction on error
            DB::rollBack();

            // Log the error
            Log::error('Product import failed: ' . $e->getMessage());

            return response()->json([
                'status' => 'error',
                'message' => 'Failed to import products',
                'error' => $e->getLine().':'.$e->getMessage(),
            ], 500);
        }
    }
}